package com.sonic.db.dao;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.sonic.db.utils.MQHibernateUtil;
import com.sonic.dto.db.MqtMobileClients;
import com.sonic.dto.ws.services.login.MQLoginRequest;
import com.sonic.dto.ws.services.login.MQLoginResponse;
import com.sonic.log.ejb.impl.MQLogger;

public class MQLoginDAO {
	private static MQLogger logger = new MQLogger(MQLoginDAO.class, "MQ-LOGIN-DAO");
	
	private Session session;
	
	private Object ownership;
	
	public MQLoginDAO() {
		try {
			ownership = MQHibernateUtil.createSession();
			session = MQHibernateUtil.getSession();
		} catch (Exception e) {
			logger.debug("MQLoginDAO", "Could not create database session, exception: " + e.getMessage());
		}
	}
	
	public MQLoginResponse doAuthorization(MQLoginRequest request) {
		final String methodName = "doAuthorization()";
		MQLoginResponse response = new MQLoginResponse();
		Transaction transaction = session.beginTransaction();
		transaction.begin();
		Criteria criteria = session.createCriteria(MqtMobileClients.class).add(
		        Restrictions.and(Restrictions.eq("login", request.getUserLogin()), Restrictions.eq("password", request.getUserPassword())));
		
		MqtMobileClients result = (MqtMobileClients) criteria.uniqueResult();
		if (result != null) {
			logger.debug(methodName, " --- User: " + request.getUserLogin() + " has been found.");
			response.setLoginStatusCode(0);
			response.setClientID(result.getClientId());
			response.setLoginStatusMsg("User: " + request.getUserLogin() + " has been found.");
			response.setLoginToken(String.valueOf((request.getUserLogin() + request.getUserPassword()).hashCode()));
		} else {
			logger.debug(methodName, " --- User: " + request.getUserLogin() + " has not been found.");
			response.setLoginStatusCode(-1);
			response.setLoginStatusMsg("User: " + request.getUserLogin() + " has not been found.");
			response.setClientID(-1);
			response.setLoginToken("");
		}
		session.clear();
		transaction.commit();
		return response;
	}
	
	public void releaseResources() {
		try {
			MQHibernateUtil.closeSession(ownership);
		} catch (Exception e) {
			logger.debug("MQLoginDAO", "Could not destroy database session, exception: " + e.getMessage());
		}
	}
}